﻿using System.Web.Mvc;
using Olemas.DataModels;
using Olemas.ViewModels;

namespace Olemas.Controllers
{
    public class TestsController : Controller
    {
        private const int PageSize = 8;
        private TestsViewModel _testsViewModel;

        //
        // GET: /Tests/Energeetikateaduskond || GET: /Tests/

        /// <summary>
        /// Returns the main view for the tests.
        /// </summary>
        /// <param name="fac">The name of the faculty to load tests for.</param>
        [OutputCache(Duration = 60)]
        public ActionResult Index(string fac)
        {
            var currentFacultyId = FacultyModel.GetFacultyId(fac);
            if (fac != null && currentFacultyId == 0)
            {
                return new HttpNotFoundResult();
            }
            var totalTests = TestModel.GetNumberOfTests(currentFacultyId);

            var totalPages = GlobalViewModel.GetTotalPages(totalTests, PageSize);

            var pagesRemaining = GlobalViewModel.RemainingPages(totalPages, 1);

            _testsViewModel = new TestsViewModel(null, currentFacultyId, 1, totalPages, pagesRemaining);
            return View("Index", _testsViewModel);
        }

        /// <summary>
        /// Returns partial view of recentTests to be updated with ajax.
        /// </summary>
        /// <param name="page">The page number to load tests for.</param>
        /// <param name="facId">The Id of the faculty to load the tests for.</param>
        /// <param name="ordering">What to order the tests by.</param>
        public ActionResult RecentTests(int page, int facId, string ordering)
        {
            var tests = TestModel.GetTests(facId, page, PageSize, ordering);

            var totalTests = TestModel.GetNumberOfTests(facId);

            var totalPages = GlobalViewModel.GetTotalPages(totalTests, PageSize);

            var pagesRemaining = GlobalViewModel.RemainingPages(totalPages, page);

            _testsViewModel = new TestsViewModel(tests, facId, page, totalPages, pagesRemaining);
            return PartialView("_RecentTests", _testsViewModel);
        }
    }
}
